//--------------------------------------------------------------
//
// Qizhi Zhang 
// ezhung@gmail.com
// http://www.moorwind.com
//
//--------------------------------------------------------------
package reader.services
{
	import __AS3__.vec.Vector;
	
	import cn.myspace.MyspaceService;
	import cn.myspace.data.AccessToken;
	import cn.myspace.data.Album;
	import cn.myspace.data.AlbumPhotos;
	import cn.myspace.data.Albums;
	import cn.myspace.data.BlogData;
	import cn.myspace.data.BlogResponseXml;
	import cn.myspace.data.CreatephotoxmlResult;
	import cn.myspace.data.Friend;
	import cn.myspace.data.Friends;
	import cn.myspace.data.Photo;
	import cn.myspace.data.Photos;
	import cn.myspace.events.MyspaceServiceEvent;
	import cn.myspace.methodgroups.FriendsListMethods;
	import cn.myspace.utils.Page;
	
	import flash.display.DisplayObject;
	import flash.events.IOErrorEvent;
	
	import mx.controls.Alert;
	import mx.core.UIComponent;
	import mx.formatters.DateFormatter;
	import mx.managers.PopUpManager;
	
	import reader.ApplicationFacade;
	import reader.core.ReaderResource;
	import reader.core.ReaderModelLocator;
	import reader.events.MyspaceEvent;
	import reader.model.IDraftProxy;
	import reader.model.IServiceProxy;
	import reader.model.vo.AlbumPhotosVO;
	import reader.model.vo.AlbumVO;
	import reader.model.vo.BlogDraftVO;
	import reader.model.vo.BlogSourceVO;
	import reader.model.vo.MediaVO;
	import reader.model.vo.PhotoVO;
	import reader.model.vo.ServiceVO;
	import reader.model.vo.UploadPhotoVO;
	import reader.utils.CryptoUtil;
	import reader.utils.URL;
	import reader.view.components.NeedMyspaceID;
	

	public class MyspaceCnReaderService extends AbstractService 
										 implements IGetAlbumAble, IPostBlogAble, IUploadPhotoAble, ISubscribeAble
	{
		////////////////////////////////////////////////////////////////////////////////
		//private variables
		
		private var _isGetAlbumAble:Boolean;
		private var _isPostBlogAble:Boolean;
		private var _isUploadPhotoAble:Boolean;
		private var _isSubscribeAble:Boolean;
		
		private var _service:MyspaceService;
		private var _draftProxy:IDraftProxy;
		private var _myspaceTokenRequester:MyspaceTokenRequester;
		
		//////////////////////////////////////////////////////////////////////////////
		//constructor
		public function MyspaceCnReaderService(service:ServiceVO, proxy:IServiceProxy, parent:UIComponent = null)
		{
			super(service, proxy, parent);
			this.initialize();
		}
		
		////////////////////////////////////////////////////////////////////////////////
		//methods
		
		//----------------------------------------------------------------------------
		//
		// service initialize
		//
		//----------------------------------------------------------------------------
		
		private var loginInitCount:uint = 0;
		override protected function initialize():void
		{
			if(service.postid <= 0)
			{
				if(loginInitCount < 5)
				{
					inputMyspaceId(parent, onInitMyspaceId);
					loginInitCount++
				}
				else return;
			}
			else
			{
				_service = new MyspaceService(service.postid, service.key, CryptoUtil.decrypt(service.secret, SERVICE_SECRET));
				_service.addEventListener(IOErrorEvent.IO_ERROR, onServiceError_handler, false, 0, true);
				_myspaceTokenRequester = new MyspaceTokenRequester(_service, service, proxy);
			}
		}
		
		private function inputMyspaceId(parent:DisplayObject, callback:Function):void
		{
			var window:NeedMyspaceID = PopUpManager.createPopUp(parent, NeedMyspaceID, true) as NeedMyspaceID;
			PopUpManager.centerPopUp(window);
			window.addEventListener(MyspaceEvent.USER_ID_GET, function(e:MyspaceEvent):void
			{
				callback(e.userid);
			}
			, false, 0, true);
		}
		
		private function onInitMyspaceId(postid:int):void
		{
			this.service.postid = postid;
			proxy.updateService(service);
			initialize();
		}
		
		//----------------------------------------------------------------------------
		//
		// get albums
		//
		//----------------------------------------------------------------------------

		public function get isGetAlbumAble():Boolean
		{
			return _isGetAlbumAble;
		}
		
		public function set isGetAlbumAble(value:Boolean):void
		{
			_isGetAlbumAble = value;
		}
		
		public function getAlbums():void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			_service.addEventListener(MyspaceServiceEvent.USERS_GET_ALBUMS, onUserGetAlbums_handler);
			_service.user.getAlbums(new Page("1", "50"));
		}
		private function onUserGetAlbums_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_GET_ALBUMS, onUserGetAlbums_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var albums:Albums = e.data as Albums;
			var list:Vector.<AlbumVO> = new Vector.<AlbumVO>();
			for(var i:int = 0; i < albums.list.length; i++)
			{
				var av:AlbumVO = new AlbumVO();
				var ab:Album = albums.list[i];
				av.albumid = ab.albumid.toString();
				av.albumuri = ab.albumuri;
				av.defaultimage = ab.defaultimage;
				av.title = ab.title;
				av.photosCount = ab.photosCount;
				list.push(av);
			}
			proxy.sendNotification(ApplicationFacade.GET_ALBUMS, list, service.name);
		}
		
		public function getAlbumPhotos(param:AlbumVO):void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			_service.addEventListener(MyspaceServiceEvent.USERS_GET_ALBUMPHOTOS, onUserGetAlbumPhotos_handler);
			_service.user.getAlbumPhotos(int(param.albumid), new Page("1", "100"));
		}
		private function onUserGetAlbumPhotos_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_GET_ALBUMPHOTOS, onUserGetAlbumPhotos_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var albums:AlbumPhotos = e.data as AlbumPhotos;
			var ap:AlbumPhotosVO = new AlbumPhotosVO();
			ap.defaultimage = albums.defaultimage;
			ap.title = albums.title;
			ap.photosCount = albums.photosCount;
			for(var i:int = 0; i < albums.list.length; i++)
			{
				var av:PhotoVO = new PhotoVO();
				var ph:Photo = albums.list[i];
				av.caption = ph.caption;
				av.imageuri = ph.imageuri;
				av.photoid = ph.photoid.toString();
				av.smallimageuri = ph.smallimageuri;
				ap.list.push(av);
			}
			proxy.sendNotification(ApplicationFacade.GET_ALBUM_PHOTOS, ap, service.name);
		}
		
		
		//----------------------------------------------------------------------------
		//
		// upload photo
		//
		//----------------------------------------------------------------------------
		
		public function get isUploadPhotoAble():Boolean
		{
			return _isUploadPhotoAble;
		}
		
		public function set isUploadPhotoAble(value:Boolean):void
		{
			_isUploadPhotoAble = value;
		}
		
		private var file:UploadPhotoVO;
		private var filename:String;
		public function uploadPhotos(file:UploadPhotoVO, album:AlbumVO = null):void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			this.file = file;
			_myspaceTokenRequester.request(uploadPhoto);
		}		
		private function uploadPhoto(token:String):void
		{
			_service.addEventListener(MyspaceServiceEvent.USERS_UPLOAD_PHOTOS, onUserUploadPhoto_handler);
			_service.user.uploadPhotos(file.image, file.extension, token);
			filename = file.fileName;
			file = null;
		}
		private function onUserUploadPhoto_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_UPLOAD_PHOTOS, onUserUploadPhoto_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var res:CreatephotoxmlResult = e.data as CreatephotoxmlResult;
			_service.addEventListener(MyspaceServiceEvent.USERS_GET_PHOTOS, onUserGetPhoto_handler);
			_service.user.getPhoto(res.photoid);
		}
		private function onUserGetPhoto_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_GET_PHOTOS, onUserGetPhoto_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var photos:Photos = e.data as Photos;
			var ph:Photo = photos.list[0];
			var av:PhotoVO = new PhotoVO();
			if(ph)
			{
				av.caption = ph.caption;
				av.imageuri = ph.imageuri;
				av.photoid = ph.photoid.toString();
				av.smallimageuri = ph.smallimageuri;	
			}
			var media:MediaVO = new MediaVO(av);
			media.name = filename;
			media.platform = service.name;
			iDraftProxy.saveMedia(media);
			proxy.sendNotification(ApplicationFacade.UPLOAD_PHOTO, av, service.name);
			filename = null;
		}	
			
		//----------------------------------------------------------------------------
		//
		// post blog
		//
		//----------------------------------------------------------------------------
		
		public function get iDraftProxy():IDraftProxy
		{
			return _draftProxy;
		}
		
		public function set iDraftProxy(proxy:IDraftProxy):void
		{
			_draftProxy = proxy;
		}
		
		public function get isPostBlogAble():Boolean
		{
			return _isPostBlogAble;
		}
		
		public function set isPostBlogAble(value:Boolean):void
		{
			_isPostBlogAble = value;
		}
		
		private var _blogDraft:BlogDraftVO;
		public function newBlog(blog:BlogDraftVO):void
		{
			_blogDraft = blog;
			if(!_service)
			{
				initialize();
				return;
			}
			
			_myspaceTokenRequester.request(postBlog);
		}
		
		private function postBlog(token:String):void
		{
			var blog:BlogData = new BlogData(_blogDraft.title, _blogDraft.description);
			_service.addEventListener(MyspaceServiceEvent.USERS_POST_BLOG, onUserPostBlog_handler);
			_service.user.postBlog(blog, token);
			
		}
		private function onUserPostBlog_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_POST_BLOG, onUserPostBlog_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var response:BlogResponseXml = e.data as BlogResponseXml;
			var blogid:String = response.uri.toLowerCase().split("blogs/")[1];
			_blogDraft.postid = blogid;
			var format:DateFormatter = new DateFormatter();
			format.formatString = "YYYY/MM/DD/";
			var date:Date = new Date();
			var link:String = "http://blog.myspace.cn/" + service.postid + "/archive/" + format.format(date) + blogid + ".aspx";
			_blogDraft.link = link;
			_blogDraft.pubDate = date;
			_blogDraft.creatDate = date;
			_blogDraft.updateDate = date;
			_blogDraft.platformid = 1;
			_blogDraft.platforms = service.name;
			_blogDraft.deleteAble = false;
			_blogDraft.editAble = false;
			_draftProxy.publishDraft(_blogDraft);
			proxy.sendNotification(ApplicationFacade.DRAFT_PUBLISHED, _blogDraft, service.name);
			_blogDraft = null;
		}
		
		//----------------------------------------------------------------------------
		//
		// add Subscribe
		//
		//----------------------------------------------------------------------------
		
		public function get isSubscribeAble():Boolean
		{
			return _isSubscribeAble;
		}
		
		public function set isSubscribeAble(value:Boolean):void
		{
			_isSubscribeAble = value;
		}
		
		public function addSubscribe():void
		{
			if(!_service)
			{
				initialize();
				return;
			}
			_service.addEventListener(MyspaceServiceEvent.USERS_GET_FRIENDS, onUserGetFriends_handler);
			_service.user.getFriends(null, null, FriendsListMethods.TOP);
		}
		private function onUserGetFriends_handler(e:MyspaceServiceEvent):void
		{
			_service.removeEventListener(MyspaceServiceEvent.USERS_GET_FRIENDS, onUserGetFriends_handler);
			if(!e.success)
			{
				Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
				return;
			}
			var fl:Friends = e.data as Friends;
			var list:Vector.<BlogSourceVO> = new Vector.<BlogSourceVO>();
			for(var i:int = 0; i < fl.list.length; i++)
			{
				var fr:Friend = fl.list[i];
				var bs:BlogSourceVO = new BlogSourceVO();
				bs.blogLink = "http://blog.myspace.cn/" + fr.userid;
				bs.blogName = fr.displayname;
				bs.blogRSS = "http://blog.myspace.cn/" + fr.userid + "/Rss.aspx?fuseaction=rss.subscriptions";
				bs.lastPubDate = BlogSourceVO.createLastPubDate();
				list.push(bs);				
			}
			proxy.sendNotification(ApplicationFacade.SERVICE_SUBSCRIBES, list, service.sid.toString());
		}
		
	}
}

import reader.utils.URL;
import reader.model.vo.ServiceVO;
import reader.model.IServiceProxy;

import cn.myspace.MyspaceService;
import cn.myspace.events.MyspaceServiceEvent;
import cn.myspace.data.AccessToken;

import mx.controls.Alert;
import mx.core.UIComponent;
import reader.core.ReaderResource;
import reader.core.ReaderModelLocator;

class MyspaceTokenRequester
{
	////////////////////////////////////////////////////////////////////////////////
	//private variables
	
	private var myspace:MyspaceService;
	private var service:ServiceVO;
	private var callback:Function;
	private var proxy:IServiceProxy;
	private var parent:UIComponent;
	
	//////////////////////////////////////////////////////////////////////////////
	//constructor
	public function MyspaceTokenRequester(myspace:MyspaceService, service:ServiceVO, proxy:IServiceProxy, parent:UIComponent = null)
	{
		this.myspace = myspace;
		this.service = service;
		this.proxy = proxy;
		this.parent = parent;
	}
	
	////////////////////////////////////////////////////////////////////////////////
	//methods
		
	public function request(callback:Function):void
	{
		this.callback = callback;
		myspace.addEventListener(MyspaceServiceEvent.OAUTH_TOKEN_REQUEST, onGetRequestToken_handler);
		myspace.addEventListener(MyspaceServiceEvent.OAUTH_TOKEN_ACCESS, onGetToken_handler);
		myspace.accessToken.getRequestToken();
	}
	
	private function onGetRequestToken_handler( e:MyspaceServiceEvent ):void
	{
		myspace.removeEventListener(MyspaceServiceEvent.OAUTH_TOKEN_REQUEST, onGetRequestToken_handler);
		if(!e.success)
		{
			Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
			return;
		}
		
		var token:AccessToken = e.data as AccessToken;
		var accessURL:String = MyspaceService.END_POINT.authorizeToken + "?oauth_callback=" 
								+ encodeURIComponent( ReaderModelLocator.instance.adCallBack ) + "&oauth_token=" 
								+ encodeURIComponent( token.token );
		service.login_url = accessURL;
		proxy.requestAuthWindow(service, authCallBack);						
	}
	private function authCallBack(url:URL):void
	{
		var token:String = url.getQueryByName( "oauth_token" );
		myspace.accessToken.getAccesToken(token);
		
	}
	private function onGetToken_handler( e:MyspaceServiceEvent ):void
	{
		myspace.removeEventListener(MyspaceServiceEvent.OAUTH_TOKEN_ACCESS, onGetToken_handler);
		if(!e.success)
		{
			Alert.show(ReaderResource.instance.resource.insertPhotoupServiceError, "", 4, parent);
			return;
		}
		
		var _token:AccessToken = e.data as AccessToken;
		if(callback != null)
		{
			callback(_token.token);
		}
		
	}
}